//
//  JZChargeHomeVC.m
//  JFTwxsd
//
//  Created by Peter on 2018/4/10.
//  Copyright © 2018年 junfeiweiyejiaoyujituan. All rights reserved.
//

#import "JZChargeHomeVC.h"
#import "JZChargeHomeCell.h"
#import "JZChargeHomeHeaderView.h"
#import "JZChargeRecordVC.h"
#import <AddressBookUI/AddressBookUI.h>
#import "NSArray+Util.h"
#import "JZChargeResultDescpVC.h"

@interface JZChargeHomeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ABPeoplePickerNavigationControllerDelegate,UITextFieldDelegate,UIViewControllerTransitioningDelegate>{
    NSInteger i;
}

@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UILabel *phoneTypeLab;
@property (weak, nonatomic) IBOutlet UICollectionView *mainCollectionView;
@property (strong, nonatomic) JZChargeHomeHeaderView *headerView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;


///话费数据源
@property (strong, nonatomic) NSArray *phoneArr;
///流量数据源
@property (strong, nonatomic) NSArray *flowArr;

///电话号
@property (copy, nonatomic) NSString *phoneStr;

@end

@implementation JZChargeHomeVC

static NSString * const headerId = @"JZChargeHomeHeaderView";
static NSString * const footerId = @"JZChargeHomeFooterView";

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configVariable];
    [self configNav];
    [self configTextField];
    [self configCollectionView];
    [self requestListData:_phoneStr];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneChargeCallBack:) name:@"phoneCharge" object:nil];
}

- (void)configVariable {
    //0
//    _phoneStr = [LoginUser shareLoginUser].phone;
    //1
//    [self checkUserPhone:^NSString *{
//        return _phoneStr = [LoginUser shareLoginUser].phone ? [LoginUser shareLoginUser].phone : @"";
//    }];
    //2
//    [self checkUserPhone:^BOOL(NSString *phone) {
//        return phone ? YES : NO;
//    }];
    //3
    _phoneStr = [self checkUserPhone:^BOOL(NSString *phone) {
        if (phone) {
            return YES;
        } else {
            return NO;
        }
    }];
    _phoneArr = [NSArray array];
    _flowArr = [NSArray array];
}

//3
- (NSString *)checkUserPhone:(BOOL (^ NS_NOESCAPE)(NSString *))phoneClosure {
    return @"";
}

//2
//- (void)checkUserPhone:(BOOL(^ NS_NOESCAPE)(NSString *))phoneClosure {
//    if (phoneClosure([LoginUser shareLoginUser].phone)) {
//        _phoneStr = [LoginUser shareLoginUser].phone;
//    } else {
//        _phoneStr = @"";
//    }
//}

//1
//- (void)checkUserPhone:(NSString *(^ NS_NOESCAPE)(void))phoneClosure {
//    phoneClosure();
//}

- (void)configTextField {
    i = 0;

    [_phoneNumTF addTarget:self action:@selector(textFieldDidEditing:) forControlEvents:UIControlEventEditingChanged];
}

- (void)configNav {

    UIButton *chargeDetailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    chargeDetailBtn.frame = CGRectMake(0, 0, 60, 45);
    [chargeDetailBtn setTitle:@"充值记录" forState:UIControlStateNormal];
    [chargeDetailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    chargeDetailBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [chargeDetailBtn addTarget:self action:@selector(chargeDetail) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:chargeDetailBtn],];
}

- (void)configCollectionView {
//    if (CGSizeEqualToSize([UIScreen mainScreen].bounds.size, CGSizeMake(320, 568))) {
//        _flowLayout.itemSize = CGSizeMake(86, 51);
//    } else if (CGSizeEqualToSize([UIScreen mainScreen].bounds.size, CGSizeMake(320, 480))) {
//        _flowLayout.itemSize = CGSizeMake(86, 51);
//    } else {
//        _flowLayout.itemSize = CGSizeMake(106, 51);
//    }
    CGFloat width = 66;
    
    _flowLayout.minimumLineSpacing = 10;
    _flowLayout.minimumInteritemSpacing = 5;

    _flowLayout.itemSize = CGSizeMake(width, width * (51.0 / 106.0));
    _flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
}

#pragma mark --------充值记录
- (void)chargeDetail {

}

#pragma mark ---------通讯录
- (IBAction)phoneBookAction:(id)sender {
    ABPeoplePickerNavigationController *picker =[[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    __weak typeof(self)weakSelf = self;
    ABAddressBookRef bookref = ABAddressBookCreateWithOptions(NULL, NULL);
    if (status == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(bookref, ^(bool granted, CFErrorRef error) {
            if (error) {
            
            }
            if (granted) {
                [weakSelf presentViewController:picker animated:YES completion:nil];
            } else {
               
            }
        });
    }else if (status == kABAuthorizationStatusAuthorized) {
        [weakSelf presentViewController:picker animated:YES completion:nil];
    } else {
        //TODO
        
    }
}

#pragma mark - 跳转到设置
- (void)sureButtonAction {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}
///这个方法在用户取消选择时调用
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [self dismissViewControllerAnimated:YES completion:^{}];
}

///这个方法在用户选择一个联系人后调用
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
    [self displayPerson:person];
    [self dismissViewControllerAnimated:YES completion:^{}];
}

///获得选中person的信息
- (void)displayPerson:(ABRecordRef)person {
    NSString *firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *middleName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
    NSString *lastname = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSMutableString *nameStr = [NSMutableString string];
    if (lastname!=nil) {
        [nameStr appendString:lastname];
    }
    if (middleName!=nil) {
        [nameStr appendString:middleName];
    }
    if (firstName!=nil) {
        [nameStr appendString:firstName];
    }
    
    NSString* phone = nil;
    ABMultiValueRef phoneNumbers = ABRecordCopyValue(person,kABPersonPhoneProperty);
    if (ABMultiValueGetCount(phoneNumbers) > 0) {
        phone = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, 0);
    } else {
        phone = @"[None]";
    }
    
    ///可以把-、+86、空格这些过滤掉
    NSString *phoneStr = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"+86" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@")" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"（" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"）" withString:@""];
    
    _phoneStr = phoneStr;
    
}

#pragma mark --------collection方法

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        if (_phoneArr.count > 0) {
            return _phoneArr.count;
        }
    } else if (section == 1) {
        if (_flowArr.count > 0) {
            return _flowArr.count;
        }
    }
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(11, 30);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return CGSizeMake(0, 0);
    }
    return CGSizeMake(0, 5);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)method:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {///充话费
        if (_phoneArr.count > 0) {
            [self requestPhoneCount:_phoneArr[indexPath.row] type:@"充话费"];
        }
    } else if (indexPath.section == 1) {///充流量
        if (_flowArr.count > 0) {
            [self requestPhoneCount:_flowArr[indexPath.row] type:@"充流量"];
        }
    }
}

///支付页
- (void)goToPay:(NSString *)count orerId:(NSString *)orderId {
   
    __weak typeof(self)weakSelf = self;
   
}

#pragma mark -------- 手机充值回调
- (void)phoneChargeCallBack:(NSNotification *)notify {
    NSDictionary *dic = (NSDictionary *)notify.object;
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"JZChargeSb" bundle:nil];
    JZChargeResultDescpVC *vc = [sb instantiateViewControllerWithIdentifier:@"JZChargeResultDescpVC"];
    if ([dic[@"data"][@"logicStatus"] isEqualToString:@"01"]) {
        vc.chargeResult = @"交易成功";
    } else {
        vc.chargeResult = @"交易中";
    }
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 模态
- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source {
    
    return nil;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        _headerView = [_mainCollectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId forIndexPath:indexPath];
        [_headerView initHeaderView:indexPath];
        return _headerView;
    }
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId forIndexPath:indexPath];
        return footer;
    }
    return [UICollectionReusableView new];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JZChargeHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JZChargeHomeCell" forIndexPath:indexPath];
    [cell configCellContent:indexPath];
    if (indexPath.section == 0) {
        [cell configCellData:_phoneArr];
    } else if (indexPath.section == 1) {
        [cell configCellData:_flowArr];
    }
    return cell;
}

#pragma mark--------textfield方法

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"JZChangeCollectionCellStyle" object:@1];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *inputString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (inputString.length > 13) {
        return NO;
    }
    if (inputString.length < 13) {
        _phoneTypeLab.text = @"";
        [[NSNotificationCenter defaultCenter] postNotificationName:@"JZChangeCollectionCellStyle" object:@1];
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //    [self.view hitTest:<#(CGPoint)#> withEvent:<#(nullable UIEvent *)#>];
}

///输入手机号加空格
- (void)textFieldDidEditing:(UITextField *)textField {
    if (textField == _phoneNumTF) {
        if (textField.text.length > i) {
            if (textField.text.length == 4 || textField.text.length == 9 ) {//输入
                NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
                [str insertString:@" " atIndex:(textField.text.length-1)];
                textField.text = str;
            }if (textField.text.length >= 13 ) {//输入完成
                textField.text = [textField.text substringToIndex:13];
                [textField resignFirstResponder];
                NSString *mobileNum = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
               
            }
            i = textField.text.length;
            
        }else if (textField.text.length < i){//删除
            if (textField.text.length == 4 || textField.text.length == 9) {
                textField.text = [NSString stringWithFormat:@"%@",textField.text];
                textField.text = [textField.text substringToIndex:(textField.text.length-1)];
            }
            i = textField.text.length;
        }
    }
}

#pragma mark --------网络请求

///列表请求
- (void)requestListData:(NSString *)phoneNum {
    __weak typeof(self) weakSelf = self;
    
    NSDictionary *paramDic = @{@"phoneNum":phoneNum};
   
}

///手机充话费、充流量请求
- (void)requestPhoneCount:(NSDictionary *)dataDic type:(NSString *)type{
    __weak typeof(self) weakSelf = self;
    
    NSDictionary *paramDic;
    NSString *api = @"";

    
}

@end
